class maxQuest {
    constructor(limit){
        this.queue = [];
        this.maxCount = limit;
        this.runCounts = 0;

    }

    add(request){
        this.queue.push(request);
    }

    taskStart() {
        for(let i = 0; i<this.maxCount; i++){
            this.runQuest();
        }
    }

    runQuest() {
        if(!this.queue.length || this.runCounts >=this.maxCount) {
            return;
        }
        this.runCounts++;
        this.queue.shift()().then(()=>{
            this.runCounts--;
            this.runQuest();
        })
    }
}


// const request = new maxQuest(2);
// request.add(request1);
// request.add(request3);
// request.add(request2);
// request.add(request4);
// request.taskStart();


function limitQuest(maxLimit, promiesLists){

    return new Promise((resolve, reject) => {
        let res = [];
        let currentIndex = 0;
        
        function processNext() {
            console.log("currentIndex", currentIndex);
            let runPromises = [];
            while(runPromises.length < maxLimit && currentIndex < promiesLists.length){
                console.log("addPromises", currentIndex);
                runPromises.push(promiesLists[currentIndex++]);
            }

            Promise.all(runPromises).then(
                data => {
                    console.log("data", data);
                    res.push(data);
                    console.log("rescurrentIndex", currentIndex);
                    if(currentIndex<promiesLists.length){
                        processNext();
                    } else{
                        resolve(res);
                    }
                }
            )
        }
        processNext();
    })
}

let request1 = new Promise((resolve, reject) =>{
        resolve('"request1"');
    }).then(()=>{
        console.log("request1")
    });
let request2 =  new Promise((resolve, reject) =>{
        resolve("reques2");
    }).then(()=>{
        console.log("request2")
    });

let request3 = new Promise((resolve, reject) =>{
        resolve("request3");
    }).then(()=>{
        console.log("request3")
    });
let request4 = new Promise((resolve, reject) =>{
        resolve("request4");
    }).then(()=>{
        console.log("request4")
    });


limitQuest(2, [request1, request3, request2, request4]);

// let p1 = new Promise((resolve, reject) => {
// resolve('成功了')
// })

// let p2 = new Promise((resolve, reject) => {
// resolve('success')
// })

// let p3 = Promise.reject('失败')

// Promise.all([p1, p2]).then((result) => {
// console.log(result) //['成功了', 'success']
// }).catch((error) => {
// console.log(error)
// })

// Promise.all([p1,p3,p2]).then((result) => {
// console.log(result)
// }).catch((error) => {
// console.log(error) // 失败了，打出 '失败'
// })